package com.lagou.zk;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

public class ZkListen {

    private ZkClient zkClient = null;

    //初始druid连接池参数
    String druid_properties = "driverClassName=com.mysql.jdbc.Driver\n" +
            "url=jdbc:mysql://server3:3306/test1?useSSL=false&rewriteBatchedStatements=true\n" +
            "username=root\n" +
            "password=123456\n" +
            "initialSize=5\n" +
            "maxActive=10\n" +
            "maxWait=3000";

    public ZkClient getZkClient() {
        return zkClient;
    }

    //连接zk
    public void connectZk() {

        //初始化zkClient
        zkClient = new ZkClient("server1:2181,server2:2181,server3:2181");
        zkClient.setZkSerializer(new Zkserializer());

        //创建/mysql_config节点，并导入druid连接池参数
        if (!zkClient.exists("/mysql_config")) {
            zkClient.createPersistent("/mysql_config", druid_properties);
        }

        //监视/mysql_config节点的data变化
        zkClient.subscribeDataChanges("/mysql_config", new IZkDataListener() {

            //若data发生改变，mysql配置信息已被更改，重新获取数据库连接池，获取成功后进行测试
            @Override
            public void handleDataChange(String path, Object data) throws Exception {

                System.out.println("mysql配置信息已被更改，正在重新获取连接池...");
                System.out.println(path + "已被更改\n"+ data);
                DruidUtils.init((String)data);
                System.out.println("正在测试数据库连接。。。");
                DruidUtils.mysqlTest();
            }

            //若mysql配置信息已被删除，数据库连接池断开
            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println("mysql配置信息已被删除，连接池断开...");
                DruidUtils.closeDruid();
            }
        });
    }
}
